﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using Models;
using DAL;

namespace 公司CRM客户关系系统.Manager
{
    /// <summary>
    /// rolePowerDialog 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务，请取消对下行的注释。
    [System.Web.Script.Services.ScriptService]
    public class rolePowerDialog : System.Web.Services.WebService
    {

        /// <summary>
        /// 根据角色ID，得到角色名称
        /// </summary>
        /// <param name="roleID"></param>
        /// <returns></returns>
        [WebMethod]
        public string GetRoleName(int roleID)
        {
            return BaseDAL.Find<Role>(roleID).RoleName;
        }

        /// <summary>
        /// 查询出所有的菜单
        /// </summary>
        /// <returns></returns>
        [WebMethod]
        public List<MenuV2> SelectMenus(int roleID)
        {
            //查询出所有的一级菜单
            List<MenuV2> roots = BaseDAL.Select<MenuV2>("select *, null SubMenus, cast(isnull((select count(*) from rolePowers where roleid=" + roleID + " and menuid=m.id),0) as bit) as Checked from menu m where parentid=0");
            //查询出所有的二级菜单
            foreach (MenuV2 menu in roots)
            {
                menu.SubMenus = BaseDAL.Select<MenuV2>("select *, null SubMenus, cast(isnull((select count(*) from rolePowers where roleid=" + roleID + " and menuid=m.id),0) as bit) as Checked from menu m where parentid=" + menu.ID);
            }
            return roots;
        }

        /// <summary>
        /// 更新权限
        /// </summary>
        [WebMethod]
        public void UpdatePower(int roleID, string powers)
        {
            //删除该角色原来的权限
            BaseDAL.ExecuteNonQuery("delete RolePowers where RoleID=" + roleID);
            //再添加本次勾选的权限
            if (!string.IsNullOrEmpty(powers))
            {
                //将提交上来的数据，使用逗号分割
                string[] arr = powers.Split(',');
                //循环遍历每一段
                foreach (string item in arr)
                {
                    try
                    {
                        int menuid = int.Parse(item);
                        RolePowers rp = new RolePowers();
                        rp.RoleID = roleID;
                        rp.MenuID = menuid;
                        BaseDAL.Insert(rp);
                    }
                    catch
                    {

                    }
                }

            }
        }



    }
}
